package com.taobao.pet.service.impl;

import com.taobao.basic.exception.BusinessException;
import com.taobao.basic.service.IBaiduAiAuditService;
import com.taobao.basic.service.impl.BaseServiceImpl;
import com.taobao.basic.util.*;
import com.taobao.order.domain.OrderPetAcquisition;
import com.taobao.order.mapper.OrderPetAcquisitionMapper;
import com.taobao.org.domain.Employee;
import com.taobao.org.domain.Shop;
import com.taobao.org.mapper.EmployeeMapper;
import com.taobao.org.mapper.ShopMapper;
import com.taobao.pet.domain.Pet;
import com.taobao.pet.domain.PetType;
import com.taobao.pet.domain.SearchMasterMsg;
import com.taobao.pet.domain.SearchMasterMsgAuditLog;
import com.taobao.pet.dto.AcceptDto;
import com.taobao.pet.mapper.PetMapper;
import com.taobao.pet.mapper.PetTypeMapper;
import com.taobao.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.taobao.pet.mapper.SearchMasterMsgMapper;
import com.taobao.pet.query.SearchMasterMsgQuery;
import com.taobao.pet.service.IPetTypeService;
import com.taobao.pet.service.ISearchMasterMsgService;
import com.taobao.user.domain.User;
import com.taobao.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Override
    public void publish(SearchMasterMsg smm, Long id) {
        //1.先添加到数据库t_searchMasterMsg    state:0 待审核
        // user_id   shop_id
        // 通过logininfoid查询userid
        User user = userMapper.loadByLogininfoId(id);
        smm.setUser_id(user.getId());
        smm.setNote("待审核");

        // 获取当前地址的point
        Point point = DistanceUtils.getPoint(smm.getAddress());
        Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
        smm.setShop_id(nearestShop.getId());
        searchMasterMsgMapper.save(smm);

        // 2.审核
        // 审核文本
        Boolean textBoolean = baiduAiAuditService.textAudit(smm.getTitle()+smm.getName() + smm.getAddress() + smm.getCoatColor());
        // 审核图片
        Boolean imgBoolean = baiduAiAuditService.imageAudit(smm.getResources());

        if (textBoolean && imgBoolean){
            // 审核通过
            // 1.修改状态
            smm.setState(1);
            smm.setNote("待处理");
            searchMasterMsgMapper.update(smm);

            // 2.添加审核日志
            SearchMasterMsgAuditLog searchMas = new SearchMasterMsgAuditLog();
            searchMas.setMsg_id(smm.getId());
            searchMas.setState(1);
            searchMas.setAudit_time(new Date());
            searchMas.setNote("待处理状态");

            // 审核日志
            searchMasterMsgAuditLogMapper.save(searchMas);

        }else{ // 审核失败
            // 1. 修改状态     note
            // 2. 添加审核日志
            // 审核通过
            smm.setNote("驳回，信息异常");
            searchMasterMsgMapper.update(smm);
            // 2. 添加审核日志
            SearchMasterMsgAuditLog smmal= new SearchMasterMsgAuditLog();
            smmal.setMsg_id(smm.getId());
            smmal.setState(0);
            smmal.setAudit_time(new Date());
            smmal.setNote("审核不通过，驳回，信息异常！");
            // 保存审核日志信息
            searchMasterMsgAuditLogMapper.save(smmal);
            throw new BusinessException("信息异常，请重新录入");
        }
    }
    /**
     * 待处理业务
     * @param query
     * @param id
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, Long id) {

        Employee employee = employeeMapper.loadByLogininfoId(id);
        query.setState(1);
        if (employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());
        }
        return super.pageQuery(query);

    }


    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, Long id) {
        // 查询用户id
        User user = userMapper.loadByLogininfoId(id);
        query.setUserId(user.getId());
        return super.pageQuery(query);
    }

    /**
     * 拒单
     * @param id
     */
    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    /**
     * 接单
     * @param dto
     * @param id
     */
    @Override
    public void accept(AcceptDto dto, Long id) {
        Long empId = dto.getHandler();
        Long msgId = dto.getMsgId();
        String note = dto.getNote();

        // 根据smmid查询订单，如果查的到，该订单正在处理中，
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadBySmmId(msgId);
        if(order!=null){ // 之前接单了
            throw new BusinessException("订单正在处理中。。。！");
        }
        //  1. 生成一个pet : 根据searchMasterMsg生成。
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);

        Pet pet = searchMasterMsg2Pet(searchMasterMsg);
        // 保存,保存id
        petMapper.save(pet);

        // 2. 生成一个收购订单：
        OrderPetAcquisition opa = ininOrderPetAcquisition(dto,pet,searchMasterMsg);
        // 3. 保存订单
        orderPetAcquisitionMapper.save(opa);

    }

    /**
     * 生成一个订单对象
     * @param dto
     * @param pet
     * @param smm
     * @return
     */
    private OrderPetAcquisition ininOrderPetAcquisition(AcceptDto dto, Pet pet, SearchMasterMsg smm) {
        // 创建一个订单对象，赋值
        OrderPetAcquisition order = new OrderPetAcquisition();

        // 随机生成一个订单编号
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(smm.getUser_id()));
        // 摘要
        order.setDigest("【"+smm.getTitle()+"】");
        // 最后确认时间 定时任务
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));

        order.setState(0);// 待处理
        order.setPrice(smm.getPrice());
        order.setPet_id(pet.getId());
        order.setUser_id(smm.getUser_id());
        order.setShop_id(smm.getShop_id());
        order.setAddress(smm.getAddress());
        order.setEmp_id(dto.getHandler());
        order.setSearch_master_msg_id(dto.getMsgId());
        return order;
    }

    /**
     * 通过searchMasterMsg生成一个pet
     * @param smm
     * @return
     */
    private Pet searchMasterMsg2Pet(SearchMasterMsg smm) {
        Pet pet = new Pet();
        pet.setName(smm.getName());
        pet.setCostprice(smm.getPrice());
        pet.setType_id(smm.getPetType());
        pet.setResources(smm.getResources());
        pet.setShop_id(smm.getShop_id());
        pet.setSearch_master_msg_id(smm.getId());
        return pet;
    }

}
